document.addEventListener('DOMContentLoaded', function () {
  const submitButton = document.getElementById('submitButton')
  submitButton.addEventListener('click', handleSubmit)

  // 设置租户ID默认值
  document.getElementById('tenant').value = '1001'
})

// AES 加密配置
const aseKey = '12345678'

// AES 加密函数
function encryptData(data) {
  const result = CryptoJS.AES.encrypt(
    JSON.stringify(data),
    CryptoJS.enc.Utf8.parse(aseKey),
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  ).toString()
  return result
}

async function handleSubmit() {
  const tenantId = document.getElementById('tenant').value
  const token = document.getElementById('token').value
  const environment = document.getElementById('environment').value

  if (!tenantId || !token) {
    alert('请填写完整信息')
    return
  }
  const domain = {
    test: 'gwapi.test.dahuangf.com',
    pre: 'gwapi.pre.dahuangf.com',
    prod: 'gwapi.dahuangf.com',
  }[environment]
  try {
    const response = await fetch(
      `https://${domain}/base-platform/user/switchTenant`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
        body: JSON.stringify({
          tenantId: tenantId,
        }),
      }
    )

    const data = await response.json()
    if (data.code === '401') {
      alert('Token无效，请检查')
    } else {
      console.log('切换租户成功：', data)
      const encryptedUserInfo = encryptData(data.data.userBaseInfo)
      // 使用 chrome.tabs.executeScript 在目标页面执行脚本
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.scripting.executeScript(
          {
            target: { tabId: tabs[0].id },
            function: (userInfo, token) => {
              // 设置cookie
              const onSetCookie = (name, value) => {
                const cookieDays = 30
                const expire = new Date(
                  Date.now() + cookieDays * 24 * 60 * 60 * 1000
                )
                document.cookie = [
                  `${name}=${encodeURIComponent(value)}`,
                  `expires=${expire.toUTCString()}`,
                  `path=/`,
                  ...(window.location.host.includes('.com')
                    ? [
                        `domain=${window.location.host
                          .split('.')
                          .slice(-3)
                          .join('.')}`,
                      ]
                    : []),
                ].join(';')
              }

              // 获取cookie
              const onGetCookie = (name) => {
                const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`)
                const arr = document.cookie.match(reg)
                if (arr) return decodeURIComponent(arr[2])
                return null
              }
              // 清除cookie
              const onDelCookie = (name) => {
                const exp = new Date()
                exp.setTime(exp.getTime() - 1)
                const cval = onGetCookie(name)
                if (cval != null)
                  document.cookie = [
                    `${name}=${encodeURIComponent(cval)}`,
                    `expires=${exp.toGMTString()}`,
                    `path=/`,
                    ...(window.location.host.includes('.com')
                      ? [
                          `domain=${window.location.host
                            .split('.')
                            .slice(-3)
                            .join('.')}`,
                        ]
                      : []),
                  ].join(';')
              }

              // 先清除旧的cookie
              onDelCookie('qt_u_t')
              onDelCookie('qt_u')

              // 设置新的cookie
              onSetCookie('qt_u_t', token)
              onSetCookie('qt_u', userInfo)
              console.log('所有操作完成，准备刷新页面')
              // 设置完cookie后刷新页面
              window.location.reload()
            },
            args: [encryptedUserInfo, data.data.token],
          },
          () => {
            // 在脚本执行完成后再显示成功提示并关闭popup
            alert('切换租户成功')
            window.close()
          }
        )
      })
    }
  } catch (error) {
    console.error('错误详情：', error)
    alert('请求失败：' + error.message)
  }
}
